package com.itheima.wemedia.service.impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.admin.feign.AdChannelFeign;
import com.itheima.admin.pojo.AdChannel;
import com.itheima.common.constants.BusinessConstants;
import com.itheima.common.constants.SystemConstants;
import com.itheima.common.enums.HttpCodeEnum;
import com.itheima.common.exception.LeadNewsException;
import com.itheima.common.util.RequestContextUtil;
import com.itheima.common.vo.PageResultVo;
import com.itheima.common.vo.ResultVo;
import com.itheima.wemedia.dto.WmMaterialPageRequestDto;
import com.itheima.wemedia.feign.DfsFeign;
import com.itheima.wemedia.mapper.WmMaterialMapper;
import com.itheima.wemedia.pojo.WmMaterial;
import com.itheima.wemedia.pojo.WmNewsMaterial;
import com.itheima.wemedia.service.WmMaterialService;
import com.itheima.wemedia.service.WmNewsMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @version 1.0
 * @description <p>自媒体图文素材信息 业务实现</p>
 * @package com.itheima.wemedia.service.impl
 */
@Service
@Slf4j
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Value("${fastdfs-server}")
    private String fastdfsServer;


    @Autowired
    private DfsFeign dfsFeign;

    @Autowired
    private WmNewsMaterialService wmNewsMaterialService;

    @Autowired
    private AdChannelFeign adChannelFeign;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 素材分页查询
     *
     * @param dto
     * @return
     */
    @Override
    public PageResultVo pageList(WmMaterialPageRequestDto dto) {
        //构建分页对象
        IPage<WmMaterial> pageInfo = new Page<>(dto.getPage(), dto.getSize());
        //构建查询条件
        LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WmMaterial::getUserId, RequestContextUtil.getUserId());
        wrapper.eq(BusinessConstants.WmMaterial.NOT_IS_COLLECTION != dto.getIsCollection(), WmMaterial::getIsCollection, dto.getIsCollection());
        //查询
        page(pageInfo, wrapper);
        List<WmMaterial> wmMaterials = pageInfo.getRecords();
        for (WmMaterial wmMaterial : wmMaterials) {
            wmMaterial.setUrl(fastdfsServer + wmMaterial.getUrl());
        }
        //封装对象返回

        return PageResultVo.pageResult(dto.getPage(), dto.getSize(), pageInfo.getTotal(), wmMaterials);
    }

    /**
     * 素材收藏
     *
     * @param id
     */
    @Override
    public void collect(Long id) {
        //先查询素材信息，判断素材是不是这个用户的，如果不是不给修改
        WmMaterial wmMaterial = getById(id);
        if (RequestContextUtil.getUserId() != wmMaterial.getUserId()) {
            throw new LeadNewsException(HttpCodeEnum.NO_OPERATOR_AUTH);
        }

        wmMaterial.setIsCollection(BusinessConstants.WmMaterial.IS_COLLECTION);


        updateById(wmMaterial);
    }

    /**
     * 删除素材
     *
     * @param id
     */
    @Override
    public void delete(Long id) {

        //先查询文章库里有没有该素材，如果有就不能删除
        List<WmNewsMaterial> wmNewsMaterials = wmNewsMaterialService.query().eq("material_id", id).list();
        //WmNewsMaterial wmNewsMaterial = wmNewsMaterialService.query().eq("material_id", id).one();
        WmMaterial wmMaterial = getById(id);
        if (!CollectionUtils.isEmpty(wmNewsMaterials) || RequestContextUtil.getUserId() != wmMaterial.getUserId()) {
            throw new LeadNewsException(HttpCodeEnum.NO_OPERATOR_AUTH);
        }

        System.out.println("Url() = " + wmMaterial.getUrl());
        ResultVo resultVo = dfsFeign.delete(wmMaterial.getUrl());

        if (!resultVo.isSuccess()) {
            throw new LeadNewsException("远程调用dfs删除素材失败了！" + id);
        }
        removeById(id);

    }

    /**
     * 取消素材收藏
     *
     * @param id
     */
    @Override
    public void cancelCollect(Long id) {
        //先查询素材信息，判断素材是不是这个用户的，如果不是不给修改
        WmMaterial wmMaterial = getById(id);
        if (RequestContextUtil.getUserId() != wmMaterial.getUserId()) {
            throw new LeadNewsException(HttpCodeEnum.NO_OPERATOR_AUTH);
        }
        wmMaterial.setIsCollection(BusinessConstants.WmMaterial.NOT_IS_COLLECTION);
        updateById(wmMaterial);
    }

    /**
     * 远程调用admin微服务查询频道列表信息
     *
     * @return
     */
    @Override

    public List<AdChannel> channel() {
        //先查询redis缓冲里有没有，如果没有在远程调用微服务查询
        log.info("调用了redis");
        //先判断key存不存在
        Boolean key = stringRedisTemplate.hasKey(SystemConstants.REDISKEY_CHANNELLIST);
        List<AdChannel> channelList = null;
        if (key) {
            String adChannelRedisList = stringRedisTemplate.opsForValue().get(SystemConstants.REDISKEY_CHANNELLIST);
            //将json字符串转为Java对象

            if (StringUtils.isNotEmpty(adChannelRedisList)) {
                channelList = JSON.parseArray(adChannelRedisList, AdChannel.class);
            }
        }
        //if (CollectionUtils.isEmpty(channelList)) {
        //    log.info("调用admin微服务进行查询了");
        //    //没有就调用微服务查询
        //    ResultVo<List<AdChannel>> resultList = adChannelFeign.list();
        //    if (!resultList.isSuccess()) {
        //        throw new LeadNewsException("远程调用admin微服务查询频道列表失败了！");
        //    }
        //     channelList = resultList.getData();
        //    //在将微服务调用的结果存入redis中
        //    stringRedisTemplate.opsForValue().set(SystemConstants.REDISKEY_CHANNELLIST,JSON.toJSONString(channelList));
        //}
        return channelList;
    }
}
